package view;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JButton;

import resources.ResourceProvider;

import model.User;


/**
 * Class RegisterPage display panel to register the User
 *
 */
public class RegisterPage extends JPanel {
	
	private static final long serialVersionUID = -2460769176381179838L;
	private JTextField textFieldfirstname;
	private JTextField textFieldLastname;
	private JTextField textFieldoptusername;
	private JPasswordField passwordField;
	private JPasswordField passwordFieldconfirm;
	private JTextField textFieldday;
	private JTextField textFieldmonth;
	private JTextField textFieldyear;
	private JRadioButton radioButtonMale;
	private JRadioButton radioButtonFemale;
	
	private EmailApplicationView emailApplicationView;

	/*
	 * (non-Javadoc)
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	public void paintComponent(Graphics g)
	{
		Image image = new ImageIcon("lib" + ResourceProvider.getFilePathSeperator() + "images" + ResourceProvider.getFilePathSeperator() 
				+ "register_background.jpg").getImage();
		g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }
    
	/**
	 * Constructor
	 * @param emailApplicationView the email application view reference
	 */
	public RegisterPage(EmailApplicationView emailApplicationView)
	{
	    this.emailApplicationView = emailApplicationView;
	    
	    setBounds(100, 100, 350, 150);
		this.setBorder(new EmptyBorder(5, 5, 3, 3));
		this.setLayout(null);
		
		JLabel lblFirstname = new JLabel("First Name");
		lblFirstname.setBounds(20, 30, 100, 14);
		this.add(lblFirstname);
		
		JLabel lblLastname = new JLabel("Last Name");
		lblLastname.setBounds(20, 62, 88, 14);
		this.add(lblLastname);
		
		JLabel lbloptusername = new JLabel("Email id");
		lbloptusername.setBounds(20, 94, 114, 14);
		this.add(lbloptusername);
		
		JLabel lblPassword = new JLabel("Password");
		lblPassword.setBounds(20, 127, 114, 14);
		this.add(lblPassword);
		
		JLabel lblGender = new JLabel("Gender");
		lblGender.setBounds(20, 182, 114, 14);
		this.add(lblGender);
		
		JLabel lblConfirmPassword = new JLabel("Confirm Password");
		lblConfirmPassword.setBounds(20, 155, 150, 14);
		this.add(lblConfirmPassword);
		
		textFieldfirstname = new JTextField();
		textFieldfirstname.setBounds(195, 30, 189, 20);
		this.add(textFieldfirstname);
		textFieldfirstname.setColumns(10);
		
		textFieldLastname = new JTextField();
		textFieldLastname.setColumns(10);
		textFieldLastname.setBounds(195, 62, 189, 20);
		this.add(textFieldLastname);
		
		textFieldoptusername = new JTextField();
		textFieldoptusername.setBounds(195, 94, 189, 20);
		this.add(textFieldoptusername);
		textFieldoptusername.setColumns(10);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(195, 126, 189, 20);
		this.add(passwordField);
		
		passwordFieldconfirm = new JPasswordField();
		passwordFieldconfirm.setBounds(195, 158, 189, 20);
		this.add(passwordFieldconfirm);
		
		radioButtonMale = new JRadioButton("Male");
		radioButtonMale.setBounds(195, 182, 109, 23);
		radioButtonMale.setOpaque(false);
		this.add(radioButtonMale);
		
		radioButtonFemale = new JRadioButton("Female");
		radioButtonFemale.setBounds(306, 182, 109, 23);
		radioButtonFemale.setOpaque(false);
		this.add(radioButtonFemale);
		
		JLabel lblDateOfBirth = new JLabel("Date Of Birth");
		lblDateOfBirth.setBounds(20, 214, 120, 14);
		this.add(lblDateOfBirth);
		
		textFieldday= new JTextField();
		textFieldday.setBounds(195, 214, 37, 20);
		this.add(textFieldday);
		textFieldday.setColumns(10);
		
		textFieldmonth = new JTextField();
		textFieldmonth.setBounds(249, 214, 42, 20);
		this.add(textFieldmonth);
		textFieldmonth.setColumns(10);
		
		textFieldyear = new JTextField();
		textFieldyear.setBounds(316, 214, 58, 20);
		this.add(textFieldyear);
		textFieldyear.setColumns(10);
		
		JLabel lblNewLabelDay = new JLabel("Day");
		lblNewLabelDay.setBounds(195, 239, 46, 14);
		this.add(lblNewLabelDay);
		
		JLabel lblMonth = new JLabel("Month");
		lblMonth.setBounds(252, 239, 46, 14);
		this.add(lblMonth);
		
		JLabel lblYear = new JLabel("Year");
		lblYear.setBounds(339, 239, 46, 14);
		this.add(lblYear);
		
		radioButtonMale.addActionListener(new ActionListener() {
	          
	          public void actionPerformed(ActionEvent e)
	          {
	        	  radioButtonFemale.setSelected(false);
	          }
	      });
		radioButtonFemale.addActionListener(new ActionListener() {
	          
	          public void actionPerformed(ActionEvent e)
	          {
	        	  radioButtonMale.setSelected(false);
	          }
	      });
		this.add(radioButtonMale);
		this.add(radioButtonFemale);
		
		JButton btnRegister = new JButton("Register");
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
	          
	          public void actionPerformed(ActionEvent e)
	          {
	        	  RegisterPage.this.emailApplicationView.displayLogin();
	          }
	      });
		btnRegister.setBounds(195, 290, 89, 23);
		btnCancel.setBounds(285, 290, 89, 23);
		this.add(btnRegister);
		this.add(btnCancel);
		btnRegister.addActionListener(new ActionListener() {
	          
	          public void actionPerformed(ActionEvent e)
	          {
            	  
	              if(textFieldfirstname.getText().trim().equals(""))
	                {
                	  final JPanel panel = new JPanel();
                	  JOptionPane.showMessageDialog(panel, "First Name should not be empty!", "Warning",
                	  JOptionPane.WARNING_MESSAGE);                 
                     }
	              else if(textFieldLastname.getText().trim().equals(""))
	                {
              	      final JPanel panel = new JPanel();
              	      JOptionPane.showMessageDialog(panel, "Last Name should not be empty!", "Warning",
              	      JOptionPane.WARNING_MESSAGE);
                    }
	              else if(textFieldoptusername.getText().trim().equals(""))
	                {
            	      final JPanel panel = new JPanel();
            	      JOptionPane.showMessageDialog(panel, "Email-id should not be empty!", "Warning",
            	      JOptionPane.WARNING_MESSAGE);
                    }
	              else if(new String(passwordField.getPassword()).trim().equals(""))
	                {
          	          final JPanel panel = new JPanel();
          	          JOptionPane.showMessageDialog(panel, "Password should not be empty!", "Warning",
          	          JOptionPane.WARNING_MESSAGE);
                    }
	              else if(new String(passwordFieldconfirm.getPassword()).trim().equals(""))
	                {
        	          final JPanel panel = new JPanel();
        	          JOptionPane.showMessageDialog(panel, "'Confirm Password' should not be empty!", "Warning",
        	          JOptionPane.WARNING_MESSAGE);
                    }	
	              else if(checkFistname(textFieldfirstname)==1)//first name invalid
	              {
          	          final JPanel panel = new JPanel();
          	          JOptionPane.showMessageDialog(panel, "First name should not contain spectial characters!", "Warning",
          	          JOptionPane.WARNING_MESSAGE);  
	              }
	              else if(checkLastname(textFieldLastname)==1)//last name invalid
	              {
          	          final JPanel panel = new JPanel();
          	          JOptionPane.showMessageDialog(panel, "Last name should not contain spectial characters!", "Warning",
          	          JOptionPane.WARNING_MESSAGE); 
	              }
	              else if(checkEmailIdFormat(textFieldoptusername)==1)//invalid email id
	                {
          	          final JPanel panel = new JPanel();
          	          JOptionPane.showMessageDialog(panel, "Email id is invalid!", "Warning",
          	          JOptionPane.WARNING_MESSAGE);          	  
	                }
	              else if(isCorrect(passwordField,passwordFieldconfirm)==1)//password mismatched
	                {
        		      passwordField.setText("");
        		      passwordFieldconfirm.setText("");
            	      final JPanel panel = new JPanel();
    	              JOptionPane.showMessageDialog(panel, "Password mismatched!", "Warning",
    	              JOptionPane.WARNING_MESSAGE);
	                }
	              else if(isDateValid(textFieldday,textFieldmonth,textFieldyear)==1)//date invalid
	              {
	            	  textFieldday.setText("");
	            	  textFieldmonth.setText("");
	            	  textFieldyear.setText("");
	            	   final JPanel panel = new JPanel();
	    	           JOptionPane.showMessageDialog(panel, "Date is invalid!", "Warning",
	    	           JOptionPane.WARNING_MESSAGE);
	              }
	              else
	              {
		        	   RegisterPage.this.registerUser();
	                   RegisterPage.this.emailApplicationView.displayLogin();
	            	   final JPanel panel = new JPanel();
	    	           JOptionPane.showMessageDialog(panel, "Register successful!", "Warning",
	    	           JOptionPane.WARNING_MESSAGE);
	            	  
	              }
	          }

		});
	} 
	
/**
 * validate file name
 * @param textFieldfirstname the text field for first name
 * @return return 0 if match else 1
 */
private int checkFistname(JTextField textFieldfirstname) 
{
	String Firstname = textFieldfirstname.getText();
	String FIRST_REGEX = "^[A-Za-z]+$";
    if(Firstname.matches(FIRST_REGEX))
        return 0;//true
    else
    	return 1;//true
}

/**
 * validate last name
 * @param textFieldLastname the text field for last name
 * @return return 0 if match else 1
 */
private int checkLastname(JTextField textFieldLastname) 
{
	String Lastname = textFieldLastname.getText();
	String LAST_REGEX = "^[A-Za-z]+$";
    if(Lastname.matches(LAST_REGEX))
        return 0;//true
    else
    	return 1;//true
}
	
/**
 * check if given date is valid
 * @param textFieldday day field
 * @param textFieldmonth month field
 * @param textFieldyear year field
 * @return return 0 if match else 1
 */
private int isDateValid(JTextField textFieldday,JTextField textFieldmonth, JTextField textFieldyear) 
{
	String day = textFieldday.getText();
	String month = textFieldmonth.getText();
	String year = textFieldyear.getText();
	String DAY_REGEX = "^[1-9]|[12][0-9]|3[01]$";
	String MONTH_REGEX = "^1|2|3|4|5|6|7|8|9|10|11|12$";
	String YEAR_REGEX = "^19[0-9][0-9]|20[0-9][0-9]$";
	if((day.matches(DAY_REGEX))&&(month.matches(MONTH_REGEX))&&(year.matches(YEAR_REGEX)))
	{
		return 0;//true
	}
	else if((textFieldday.getText().trim().equals(""))&&(textFieldmonth.getText().trim().equals(""))&&(textFieldyear.getText().trim().equals("")))
	{
		return 0;
	}
	else
   return 1;//false
}            	  
	           
/**
 * check if the password and confirm password same
 * @param pw1 password field
 * @param pw2 confirm password field
 * @return return 0 if match else 1
 */
private int isCorrect(JPasswordField pw1, JPasswordField pw2)
{
    char[] PW1 = pw1.getPassword();
	char[] PW2 = pw2.getPassword();
	if (PW1.length != PW2.length)
	return 1; 
	for (int i = 0; i < PW1.length; i++)
	if (PW1[i] != PW2[i])
    return 1;	
    return 0;
}

/**
 * check if email id format is correct
 * @param textFieldoptusername the text field for user name
 * @return return 0 if match else 1
 */
private int checkEmailIdFormat(JTextField textFieldoptusername)
{
	String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
	String email = textFieldoptusername.getText();
	if(email.matches(EMAIL_REGEX))
    return 0;//0 means true
	else
    return 1;//1 means false
	
}
    /**
     * register user
     */
    private void registerUser()
    {
       String first_name = textFieldfirstname.getText().trim();     
       String last_name = textFieldLastname.getText().trim();
       String user_id = textFieldoptusername.getText().trim();
       String password = new String(passwordFieldconfirm.getPassword());
       String day = textFieldday.getText().trim();
       String month = textFieldmonth.getText().trim();
       String year = textFieldyear.getText().trim();
       String sex = "";
       
       if(radioButtonMale.isSelected())
       {
           sex = "Male";
       }
       else if(radioButtonFemale.isSelected())
       {
           sex = "Female";
       }
 
       User user = new User.Builder()
       .setFirstName(first_name)
       .setLastName(last_name)
       .setId(user_id)
       .setPassword(password)
       .setBirthDay(day)
       .setBirthMonth(month)
       .setBirthYear(year)
       .setGender(sex)
       .build();
       
       this.emailApplicationView.getController().requestPersitUser(user);
    }
}

